package com.bluedot.utils;

import com.alibaba.fastjson.JSONObject;
import com.bluedot.dao.jedis.JedisUtil;
import com.sun.mail.util.MailSSLSocketFactory;
import redis.clients.jedis.Jedis;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 发送短信验证工具类
 */
public class MessageUtil {

    private static Properties prop = new Properties();
    private static String sendEmail = "924208219@qq.com";
    private static String authorizationCode = "hwgwseipsmhibfaa";

    static {
        prop.setProperty("mail.host","smtp.qq.com");///设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol","smtp");///邮件发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户密码
        //QQ邮箱需要设置SSL加密
        MailSSLSocketFactory sf= null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable","true");
        prop.put("mail.smtp.ssl.socketFactory",sf);
    }
    public static void sendMessage(String email,String content) throws MessagingException {
        //使用javaMail发送邮件的5个步骤
        //1.创建定义整个应用程序所需要的环境信息的session对象
        Session session=Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sendEmail,authorizationCode);
            }
        });
        //2.通过session得到transport对象
        Transport ts=session.getTransport();
        //3.使用邮箱的用户名和授权码连上邮件服务器
        ts.connect("smtp.qq.com",sendEmail,authorizationCode);
        //4.创建邮件：写文件
        //注意需要传递session
        MimeMessage message=new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(sendEmail));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(email));
        //邮件标题
        message.setSubject("验证信息");
        //邮件的文本内容
        message.setContent(content,"text/html;charset=UTF-8");
        //5.发送邮件
        ts.sendMessage(message,message.getAllRecipients());
        //6.关闭连接
        ts.close();
    }

    public static boolean checkCode(String code,String email){
        Jedis jedis = new JedisUtil().getJedis();
        String cCode = jedis.get(email);
        if (cCode != null && cCode.equals(cCode)){
            jedis.del(email);
            return true;
        }else {
            return false;
        }
    }


}
